import Storage from '@/lib/storage';

const ss = new Storage('', 'sessionStorage');
const Cookies = new Storage('cookie');

const state = {
    initialized: false, // true 初始化完成
    initUserInfo: false, // 是否查询了用户
};
const mutations = {
    setState: (state, data) => {
        state[data.key] = data.value;
    }
};
const actions = {
    init({commit, dispatch, rootState}, dataInfo) {
        return new Promise((resolve, reject) => {
            dispatch('getCurrentUser')
                .then(() => {
                    dispatch('checkPermission')
                        .then(res => {
                            // TODO 有权限 则进入项目，否则到无权限页
                            if (res.hasPermission) {
                                dispatch('getUserPermissions', {userId: rootState.currentUser.id, ...dataInfo}).then(() => {
                                    resolve()
                                }).catch((err) => {
                                    reject(new Error(err))
                                })
                            } else {
                                commit('meta', {
                                    pageMessage: {
                                        code: 403,
                                        message: '您不是专家库用户'
                                    }
                                }, {
                                    root: true
                                })
                            }
                        })
                })
                .catch((err) => {
                    reject(new Error(err))
                })
        })
    },
    // 获取当前登录用户信息
    getCurrentUser({commit, dispatch, rootState}, isRefresh = true) {
        const accessToken = Cookies.getItem('X-DT-accessToken') || '';
        if (!accessToken) {
            return;
        }

        return new Promise((resolve, reject) => {
            if (rootState.currentUser.userId && isRefresh) {
                return resolve(rootState.currentUser)
            }
            G_transmit('getCenterUserInfo', {})
                .then((res) => {
                    let data = res.data || {};
                    commit('meta', {currentUser: data}, {root: true})
                    commit('setState', {
                        key: 'initUserInfo',
                        value: true
                    });

                    resolve(data)
                })
                .catch((err) => {
                    reject(err)
                })
        })
    },
    // 判断当前角色
    checkPermission({state, commit, dispatch}, sysUserId) {
        return new Promise((resolve, reject) => {
            dispatch('proxyAction', {
                name: 'sysExpertCheckPermission'
            }, {
                root: true
            }).then((res) => {
                resolve(res.data)
            }).catch((err) => {
                reject(err)
            })
        })
    },
    // 获取用户权限菜单
    getUserPermissions({state, commit, dispatch}, dataInfo) {
        return new Promise((resolve, reject) => {
            ss.removeItem('BTN_PERMISSION')

            dispatch('proxyAction', {
                name: 'sysExpertUserPermission',
                data: {
                    sys: 'expert'
                }
            }, {
                root: true
            }).then((res) => {
                let permission = res.data || [];
                if(dataInfo.route){
                    let isHavePermission = res.data.findIndex(item => item.path === dataInfo.route);
                    if(isHavePermission === -1) {
                        commit('meta', {
                            pageMessage: {
                                code: dataInfo.route === 'welcome' ? 403 : 405,
                                message: '您没有当前页面权限'
                            }
                        }, {
                            root: true
                        })
                    }
                }

                commit('setState', {
                    key: 'userPermission',
                    value: {
                        sysMenuVOList: permission
                    }
                });
                commit('setState', {
                    key: 'initialized',
                    value: true
                });
                resolve(res)
            }).catch((err) => {
                reject(err)
            })
        })
    },
    // 刷新菜单 & 权限
    reload() {
        window.location.reload();
    },
};

export default {
    namespaced: true,
    state,
    mutations,
    actions,
}
